﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace NyBio.DB
{
    public class DBPropertyReflector
    {
        
        public delegate Object getHandler(Object value);
        public delegate Object setHandler(Object value);

        private string _propertyName;
        private getHandler _getHandler;
        private setHandler _setHandler;

        public DBPropertyReflector(string propertyName, getHandler _getHandler, setHandler _setHandler)
        {
            _propertyName = propertyName;
            this._getHandler = _getHandler;
            this._setHandler = _setHandler;
        }

        public string propertyName
        {
            get { return _propertyName; }
        }

        public void setValue(Object target, Object value)
        {
            try
            {
                Object result = _setHandler(value);
                PropertyInfo prop = target.GetType().GetProperty(_propertyName);
                prop.SetValue(target, result, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("DBProperty Error [ Method: Set, Object Type: " + target.GetType().ToString() + ", PropertyName: " + _propertyName + " ]: " + ex.Message);
            }
        }

        public Object getValue(Object target)
        {
            try
            {
                PropertyInfo prop = target.GetType().GetProperty(_propertyName);
                Object value = prop.GetValue(target, null);
                value = _getHandler(target);
                return value;
            }
            catch (Exception ex)
            {
                Console.WriteLine("DBProperty Error [ Method: Get, Object Type: " + target.GetType().ToString() + ", PropertyName: " + _propertyName + " ]: " + ex.Message);
                return null;
            }
        }
    }
}
